# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :base_practice.py
# @Time      :2025/6/12 20:35
# @Author    :aiyimu

from redis.cluster import RedisCluster

# 集群节点配置（至少1个节点地址）
startup_nodes = [
    {"host": "127.0.0.1", "port": 7000},
    {"host": "127.0.0.1", "port": 7001}
]

# 创建集群客户端
rc = RedisCluster(
    startup_nodes=startup_nodes,
    decode_responses=True,
    password="123456"
)

def testClusterConnect():
    # 测试集群连接
    print(rc.ping())

def testClusterOp():
    await rc.set("user:1000", "李田所")
    print(await rc.get("user:1000"))
    # 计数器
    await rc.incr("cluster_counter")

def testClusterMset():
    # 错误示例：多键操作（不同slot）
    try:
        rc.mset({"key1": "value1", "key2": "value2"})
    except redis.RedisClusterException as e:
        print(f"错误: {e}")
    # 解决方案：使用hash tag强制相同slot
    rc.mset({"{user}.name": "李田所", "{user}.age": "30"})  # 使用{}定义相同slot

def testClusterPipeline():
    # 集群管道（自动处理跨节点命令）
    pipe = rc.pipeline()
    pipe.set("product:1000", "Phone")
    pipe.incr("product:1000:views")
    pipe.expire("product:1000", 3600)
    results = await pipe.execute()

def main():
    # testClusterConnect()
    # testClusterOp()
    # testClusterMset()
    testClusterPipeline()

if __name__ == "__main__":
    main()
